package inspector

import (
	"github.com/Unixeno/TheMoon/logging"
	"github.com/Unixeno/TheMoon/planet/core/context"
	eventDao "github.com/Unixeno/TheMoon/planet/orm/event"
	"github.com/Unixeno/TheMoon/planet/orm/model"
	message "github.com/Unixeno/TheMoon/radio/protos"
	"time"
)

const ModuleName = "inspector"

var logger = logging.GetLogger(ModuleName)

type Inspector struct {
	level model.EventLevel
}

func GetModule() *Inspector {
	return &Inspector{
		level: model.LevelDebug,
	}
}

func (i *Inspector) Init() {
	context.RegisterModule(ModuleName)
}

func (i *Inspector) Start() {
	go i.worker()
}

func (i *Inspector) worker() {
	for {
		msg, err := context.RecvMessage(ModuleName)
		if err != nil {
			logger.WithError(err).Error("failed to recv message")
			return
		}
		// 反序列号消息
		event := message.Event{}
		err = event.Unmarshal(msg.Content.([]byte))
		if err != nil {
			logger.WithError(err).Error("failed to unmarshal event message")
			continue
		}
		logger.WithFields(logging.Fields{
			"moon":   msg.MoonID,
			"source": event.Source,
			"msg":    event.Message,
			"level":  model.EventLevel(event.Level),
		}).Debug("received moon event")
		// 判断消息等级来决定是否存入数据库
		if i.level.Check(model.EventLevel(event.Level)) {
			dao := eventDao.New()
			dao.Source = event.Source
			dao.Level = model.EventLevel(event.Level)
			dao.Message = event.Message
			dao.MoonID = msg.MoonID
			dao.Time = time.Unix(event.Time, 0)
			err = dao.Create()
			if err != nil {
				logger.WithError(err).Error("failed to store message")
			}
		}

		// 响应一个空message即可
		replay := msg.CreateReplay()
		_ = context.SendMessage(&replay)
	}
}
